﻿// <copyright file="ControlExtensions.cs" company="Auros Ltd.">
//     Copyright (c) Auros Ltd. All rights reserved.
// </copyright>

namespace Auros.Categorisation
{
    using System.Web.UI;
    using umbraco.cms.businesslogic.datatype;
    using System;
    using System.Web.UI.HtmlControls;

    /// <summary>
    /// Class of extension methods for System.Web.UI.Control.
    /// </summary>
    internal static class ControlExtensions
    {
        /// <summary>
        /// Recursively finds all descendant controls that are of a specified type starting within the current control.
        /// </summary>
        /// <typeparam name="T">Type of control to find.</typeparam>
        /// <param name="container">The container control.</param>
        /// <returns>Enumerable collection of controls.</returns>
        internal static System.Collections.Generic.IEnumerable<T> GetDescendantControlsByType<T>(this Control container)
        {
            return ControlHelpers.GetControlsByTypeRecursive<T>(container);
        }

        /// <summary>
        /// Registers the embedded client resource.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="resourceContainer">The type containing the embedded resource</param>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="type">The type.</param>
        internal static void RegisterEmbeddedClientResource(this Control ctl, Type resourceContainer, string resourceName, ClientDependencyType type)
        {
            var target = ctl.Page.Header;

            // if there's no <head runat="server" /> don't throw an exception.
            if (target != null)
            {
                switch (type)
                {
                    case ClientDependencyType.Css:
                        // get the urls for the embedded resources
                        var resourceUrl = ctl.Page.ClientScript.GetWebResourceUrl(resourceContainer, resourceName);
                        var link = new HtmlLink();
                        link.Attributes.Add("href", resourceUrl);
                        link.Attributes.Add("type", "text/css");
                        link.Attributes.Add("rel", "stylesheet");
                        target.Controls.Add(link);
                        break;

                    case ClientDependencyType.Javascript:
                        ctl.Page.ClientScript.RegisterClientScriptResource(resourceContainer, resourceName);
                        break;

                    default:
                        break;
                }
            }
        }
    }
}